package com.example.servletdemo.listner.session;

import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionEvent;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;

public class UserSession implements HttpSessionActivationListener,Serializable{
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    private static final String TAG = "UserSession";

    /**
     * 将Session内存中的对象持久化（序列化）到磁盘
     * @param se
     */
    @Override
    public void sessionWillPassivate(HttpSessionEvent se) {
        UserSession user= (UserSession) se.getSession().getAttribute("user");
        SimpleDateFormat df= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        System.out.println(TAG+"=>sessionWillPassivate =>将Session内存中的对象持久化（序列化）到磁盘="+user.getUsername()+":"+user.getPassword()+"=>"+df.format(new Date()));
    }

    /**
     * 将磁盘上的对象再次恢复到session内存中
     * @param se
     */
    @Override
    public void sessionDidActivate(HttpSessionEvent se) {
        UserSession user= (UserSession) se.getSession().getAttribute("user");
        SimpleDateFormat df= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        System.out.println(TAG+"=>sessionDidActivate=>将磁盘上的对象再次恢复到session内存中="+user.getUsername()+":"+user.getPassword()+"=>"+df.format(new Date()));
    }
}
